package com.liu.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.eduService.entity.EduCourse;
import com.liu.eduService.entity.EduCourseDescription;
import com.liu.eduService.entity.FrontVo.FrontCourseAllInfoVo;
import com.liu.eduService.entity.FrontVo.FrontCourseQuery;
import com.liu.eduService.entity.vo.CourseInfoVo;
import com.liu.eduService.entity.vo.CoursePublishVo;
import com.liu.eduService.entity.vo.CourseQuery;
import com.liu.eduService.mapper.EduCourseMapper;
import com.liu.eduService.service.EduChapterService;
import com.liu.eduService.service.EduCourseDescriptionService;
import com.liu.eduService.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.eduService.service.EduVideoService;
import com.liu.serviceBase.exception.MyException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author LSJ
 * @since 2022-01-07
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    @Override
    public String saveCourse(CourseInfoVo course) {

//        1\ 添加课程的基本信息
//        将 CourseInfoVo 转成 EduCourse
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(course,eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert<=0){
//            添加失败
            throw new  MyException(20001,"保存课程基本信息失败！");
        }

//        2\添加课程描述
        EduCourseDescription description = new EduCourseDescription();
        description.setId(eduCourse.getId());
        // 设置课程的id
        description.setDescription( course.getDescription());

        boolean save = descriptionService.save(description);
        if(!save){
            throw new MyException(20001, "课程详情信息保存失败");
        }
        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourse(String courseId) {

        // 由于 课程信息 与课程描述分开，故查两次
//      1、 查询课程的基本信息
        EduCourse eduCourse = baseMapper.selectById(courseId);
        if (eduCourse == null) {
            throw new MyException(20001, "该课程不存在");
        }
//      3\将课程基本信息 转换成VO
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);
//      2\ 查询该课程的描述
        EduCourseDescription courseDescription = descriptionService.getById(courseId);
        if (eduCourse != null) {
            courseInfoVo.setDescription(courseDescription.getDescription());

        }
        return courseInfoVo;
    }

    @Override
    public Boolean updateCourse(CourseInfoVo courseInfoVo) {

        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVo,eduCourseDescription);
        int update = baseMapper.updateById(eduCourse);
        if (update<=0){
            throw new MyException(20001, "该课程修改基本信息失败");
        }
        System.out.println(eduCourseDescription);
        boolean updateDescription = descriptionService.saveOrUpdate(eduCourseDescription);
        if (!updateDescription){
            throw new MyException(20001, "该课程修改简介失败");
        }
        if (update>0&&updateDescription){
            return true;
        }
        return false;

    }

    @Override
    public CoursePublishVo getCoursePublishInfo(String courseId) {

        CoursePublishVo coursePublishInfo = baseMapper.getCoursePublishInfo(courseId);
        return coursePublishInfo;
    }

    @Override
    public int publishCourse(String courseId) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(courseId);
        eduCourse.setStatus("Normal");
        int update = baseMapper.updateById(eduCourse);
//        update Edu_course set status = "Normal" where id = courseId;
        return update;
    }

        /**
            * 方法名称：pageQuery <br/>
            * 功能描述: 条件查询课程 <br/>
            * 方法参数：<br/>
            * 结果返回： <br/>
            * 创建作者：刘世锦 <br/>
            * 创建时间: 2022-01-12 15:35<br/>
            * 更新作者：2022/1/12<br/>
            * 更新信息: [序号][日期YYYY-MM-DD] [更改人姓名][变更描述] <br/>
            */
    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
//        1、 判断查询条件为空则查询全部数据
        if (courseQuery ==null){
            baseMapper.selectPage(pageParam,wrapper);
        }else {
//            2 获取 query的信息
            String title = courseQuery.getTitle();
            String teacherId = courseQuery.getTeacherId();
            String subjectParentId = courseQuery.getSubjectParentId(); // 一级类别
            String subjectId = courseQuery.getSubjectId(); //  二级类别
            String status = "Normal";

            if (!Objects.isNull(title)){
                wrapper.like("title",title);
            }
            if (!Objects.isNull(teacherId)){
                wrapper.eq("teacher_id",teacherId);
            }
            if (!Objects.isNull(subjectParentId)){
                wrapper.eq("subject_parent_id",subjectParentId);
            }
            if (!Objects.isNull(subjectId)){
                wrapper.eq("subject_id",subjectId);
            }
            if (!Objects.isNull(status)){
                wrapper.eq("status",status);
            }
            baseMapper.selectPage(pageParam,wrapper);

        }

    }

    @Override
    public Boolean DeleteCourseById(String courseId) {
        if (Objects.isNull(courseId)){
            throw new MyException(20001,"删除的courseId为空");
        }else {
//            1\ 删除小节
            eduVideoService.deletevideoBycourseId(courseId);
//            2\ 删除章节
            eduChapterService.deletechapterBycourseId(courseId);
//            3、 删除描述
            descriptionService.deleteDescriptionBycourseId(courseId);
//            4、 删除课程
            int delete = baseMapper.deleteById(courseId);
            return delete>0;
        }
    }

    @Override
    public List<EduCourse> getHostCourse() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8");
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    @Override
    public List<EduCourse> getCourseListByTeacherId(String teacherid) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.eq("teacher_id",teacherid);
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;


    }

    @Override
    public Map<String, Object> queryFrontCourse(Page<EduCourse> coursePage, FrontCourseQuery courseQuery) {
        String Normal = "Normal";
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isEmpty(courseQuery)){
            System.out.println("courseQuery:"+courseQuery);
            baseMapper.selectPage(coursePage,wrapper);

        }else {
            String title = courseQuery.getTitle();

//            一级标题
            String parentId = courseQuery.getSubjectParentId();
//            二级标题
            String subjectId = courseQuery.getSubjectId();
//             价格排序
            String priceSort = courseQuery.getPriceSort();
//             销量排序
            String buyCountSort = courseQuery.getBuyCountSort();
//             时间排序
            String gmtCreateSort = courseQuery.getGmtCreateSort();

            if (ObjectUtils.isNotEmpty(title)){
                wrapper.like("title",title);
            }
            if (ObjectUtils.isNotEmpty(parentId)){
                wrapper.eq("subject_parent_id",parentId);
            }
            if (ObjectUtils.isNotEmpty(subjectId)){
                wrapper.eq("subject_id",subjectId);
            }

            if (ObjectUtils.isNotEmpty(priceSort)){
                wrapper.orderByDesc("price");
            }

            if (ObjectUtils.isNotEmpty(buyCountSort)){
                wrapper.orderByDesc("buy_count");
            }

            if (ObjectUtils.isNotEmpty(gmtCreateSort)){
                wrapper.orderByDesc("gmt_create");
            }
            wrapper.eq("status",Normal);
            baseMapper.selectPage(coursePage,wrapper);
        }

            List<EduCourse> records = coursePage.getRecords();
    //            总页数
            long pages = coursePage.getPages();
    //            总条数
            long total = coursePage.getTotal();
            long current = coursePage.getCurrent();
            long size = coursePage.getSize();
            boolean hasNext = coursePage.hasNext();
            boolean hasPrevious = coursePage.hasPrevious();

            Map<String, Object> map = new HashMap<>();
            map.put("records",records);
            map.put("current",current);
            map.put("pages",pages);
            map.put("size",size);
            map.put("total",total);
            map.put("hasNext",hasNext);
            map.put("hasPrevious",hasPrevious);

            return map;
    }

    @Override
    public FrontCourseAllInfoVo getCourseAllInfo(String courseId) {

//        2、  每次点击课程，其浏览量就增加：
        updateCourseViewCount(courseId);
//        1、 查询课程的全部信息（根据SQL）
        FrontCourseAllInfoVo courseAllInfo  = baseMapper.getCourseAllInfo(courseId);
        return courseAllInfo;
    }

    @Override
    public void updateCourseViewCount(String courseId) {
        EduCourse course = baseMapper.selectById(courseId);
        course.setViewCount(course.getViewCount()+1);
        baseMapper.updateById(course);
    }


}
